package org.yidu.novel.controller;

import java.sql.Date;
import java.util.Calendar;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.yidu.novel.bean.RegeditForm;
import org.yidu.novel.constant.YiDuConstants;
import org.yidu.novel.controller.base.AbstractPublicBaseController;
import org.yidu.novel.entity.TUser;

@Controller
public class RegeditController extends AbstractPublicBaseController {

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    }

    @Autowired
    protected AuthenticationManager authenticationManager;

    @RequestMapping(value = "/regedit", method = RequestMethod.GET)
    public String regedit(Map<String, Object> model) {
        model.put("regeditForm", new RegeditForm());
        return "regedit";
    }

    @RequestMapping(value = "/regedit", method = RequestMethod.POST)
    @Transactional
    public String doRegedit(@Valid RegeditForm regeditForm, BindingResult bindingResult, HttpServletRequest request, HttpServletResponse response,
            ModelMap model) {

        if (bindingResult.hasErrors()) {
            return "regedit";
        }

        if (!StringUtils.equals(regeditForm.getPassword(), regeditForm.getRepassword())) {
            model.addAttribute("error", "两次输入密码不同！");
            return "regedit";
        }

        Integer count = userRepository.countByLoginId(regeditForm.getLoginId());
        if (count > 0) {
            model.addAttribute("error", "该名字已经注册过，请更换其他名字再注册！");
            return "regedit";
        }

        TUser user = new TUser();
        BeanUtils.copyProperties(regeditForm, user);
        user.setType(YiDuConstants.UserType.NORMAL_USER);
        user.setActivedFlag(true);
        user.setDeleteFlag(false);
        user.setModifyTime(new Date(Calendar.getInstance().getTimeInMillis()));

        // 登录到数据库
        userRepository.save(user);
        // authenticateUserAndSetSession(regeditForm.getUserName(),
        // regeditForm.getPassword(), request);
        return "redirect:/";
    }

    private void authenticateUserAndSetSession(String loginId, String password, HttpServletRequest request) {

        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(loginId, password);
        // generate session if one doesn't exist
        request.getSession();
        token.setDetails(new WebAuthenticationDetails(request));
        Authentication authenticatedUser = authenticationManager.authenticate(token);
        SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
    }

    @Override
    protected Map<String, Object> getBlocks() {
        return null;
    }

    @Override
    protected int getCurrentPageType() {
        return YiDuConstants.Pagetype.PAGE_REGEDIT;
    }
}
